<?php
//创建任务
function bzg_attachment_cdn_add_cron() {
	if( ! wp_next_scheduled( 'attachment_cdn' ) ) {
		wp_schedule_event( time(), 'hourly', 'attachment_cdn' );
		return true;
	} else {
		return false;
	}
}

//删除任务
function bzg_attachment_cdn_delete_cron() {
	if( wp_next_scheduled( 'attachment_cdn' ) ) {
		wp_clear_scheduled_hook( 'attachment_cdn' );
	}
}

//给CURL添加参数
function bzg_api_curl(&$handle) {
	$url = get_bloginfo( 'url' );
	$url = parse_url( $url );
	curl_setopt( $handle, CURLOPT_REFERER, $url['host'] );
}

//获取WordPress所有图片ID
function bzg_attachment_cdn_get_attachment_ids(){
	$ids = array();
	$args = array(
		'posts_per_page' => -1,
		'post_type' => 'attachment',
		'post_status' => 'closed',
	);
	$query = new WP_Query( $args );
	while ( $query->have_posts() ) {
		$query->the_post();
		$ids[] = get_the_ID();
	}
	wp_reset_postdata();
	return $ids;
}

//手动同步所有图片
function bzg_attachment_cdn_sync() {
	set_time_limit(0);
	$options = get_option( 'attachment_cdn_options' );
	$options = unserialize($options);
	$attachment_ids = get_option( 'attachment_cdn_ids' );
	if( $attachment_ids ) {
		$attachment_ids = explode( ',', $attachment_ids );
	} else {
		$attachment_ids = bzg_attachment_cdn_get_attachment_ids();
	}

	if( empty( $attachment_ids ) ) {
		bzg_attachment_cdn_delete_cron();
		return;
	}

	$up_ids = $attachment_ids;
	add_action( 'http_api_curl', 'bzg_api_curl', 10, 1 );
	$error = false;
	if($options['backupcdn']) $backup_url = $options['backupcdnscheme'] . '://' . $options['backupcdn'];
	$upload_path = get_option( 'upload_path' );
	if( ! $upload_path ) $upload_path = 'wp-content/uploads';

	foreach ( $attachment_ids as $attachment_id ) {
		$meta = wp_get_attachment_metadata( $attachment_id );
		$upload_dir = wp_upload_dir( $meta['file'] );
		//同步原图
		$originalfile = $upload_dir['basedir'] . '/' . $meta['file'];
		if( file_exists( $originalfile ) ) {
			$originalurl = $upload_dir['baseurl'] . '/' . $meta['file'];
			$original_response = wp_remote_get( $originalurl, array( 'timeout' => 30 ) );
			if($backup_url) {
				$originalurl2 = $backup_url . '/' . $upload_path . '/' . $meta['file'];
				$original_response2 = wp_remote_get( $originalurl2, array( 'timeout' => 30 ) );
			}
			if ( is_wp_error( $original_response ) || ( $backup_url && is_wp_error( $original_response2 ) ) ) {
				$error = true;
			} elseif( 'yes' == $options['delfile'] ) {
				unlink( $originalfile );
			}
		}
		//同步缩略图
		$sizes = $meta['sizes'];
		if( ! empty( $sizes ) && ! $error ) {
			foreach( $sizes as $size ) {
				if( empty( $size['file'] ) ) continue;

				$sizefile = $upload_dir['path'] . '/' . $size['file'];

				if( ! file_exists( $sizefile ) ) continue;

				$sizeurl = $upload_dir['url'] . '/' . $size['file'];
				$sizeurl_response = wp_remote_get( $sizeurl, array( 'timeout' => 30 ) );
				if($backup_url) {
					$sizeurl2 = $backup_url . '/' . $upload_path . $upload_dir['subdir'] . '/' . $size['file'];
					$sizeurl_response2 = wp_remote_get( $sizeurl2, array( 'timeout' => 30 ) );
				}
				if ( is_wp_error( $sizeurl_response )  || ( $backup_url && is_wp_error( $sizeurl_response2 ) ) ) {
					$error = true;
				} elseif( 'yes' == $options['delfile'] ) {
					unlink( $sizefile );
				}
			}
		}

		if( ! $error ) {
			$unset_key = array_search( $attachment_id, $up_ids );
			unset( $up_ids[$unset_key] );
			$up_id = implode( ',', $up_ids );
			update_option( 'attachment_cdn_ids', $up_id );
		}
	}

	delete_option( 'attachment_cdn_ids' );
	bzg_attachment_cdn_delete_cron();
}
add_action( 'attachment_cdn', 'bzg_attachment_cdn_sync' );

//替换URL
function bzg_attachment_cdn_replace_url( $content, $order = 'ASC' ) {
	if( ! $cdn_url = get_option( 'upload_url_path' ) ) return $content;

	$siteurl = get_option( 'siteurl' );
	$siteurl = trailingslashit( $siteurl );
	$upload_path = trim( get_option( 'upload_path' ) );
	if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
		$localurl = WP_CONTENT_URL . '/uploads';
	} else {
		$localurl = $siteurl . $upload_path;
	}
	if( $order == 'ASC' ) {
		$content = str_replace( $localurl, $cdn_url, $content );
	}

	if( $order == 'DESC' ) {
		$content = str_replace( $cdn_url, $localurl, $content );
	}

	return $content;
}

//过滤内容
function bzg_attachment_cdn_the_content( $content ) {
	$content = bzg_attachment_cdn_replace_url( $content );
	return $content;
}

//前台文章内容输出镜像URL
if( ! is_admin() ) {
	add_filter( 'the_content', 'bzg_attachment_cdn_the_content', 10, 1 );
	function bzg_attachment_cdn_replace( $url ) {
		$options = get_option( 'attachment_cdn_options' );
		$options = unserialize($options);
		$parse = parse_url( $url );
		$url = str_replace($parse['scheme'], $options['cdnscheme'], $url);
		return $url;
	}
	add_filter('wp_get_attachment_url', 'bzg_attachment_cdn_replace', 10, 1 );
}

//上传图片时将镜像URL替换为本地URL
function bzg_attachment_cdn_insert_attachment_data( $data, $postarr ) {
	$guid = $postarr['guid'];
	$url = bzg_attachment_cdn_replace_url( $guid, 'DESC' );
	$data['guid'] = $url;
	return $data;
}
add_filter( 'wp_insert_attachment_data', 'bzg_attachment_cdn_insert_attachment_data', 10, 2 );

//保存附件数据时执行同步图片
function bzg_attachment_cdn_update_attachment_metadata( $data ) {
	$options = get_option( 'attachment_cdn_options' );
	$options = unserialize($options);
	add_action( 'http_api_curl', 'bzg_api_curl', 10, 1 );
	$meta = $data;
	if($options['backupcdn']) $backup_url = $options['backupcdnscheme'] . '://' . $options['backupcdn'];
	$upload_dir = wp_upload_dir( $meta['file'] );
	$upload_path = get_option( 'upload_path');
	if(empty($upload_path) ) $upload_path = 'wp-content/uploads';
	$error = false;
	$originalfile = $upload_dir['basedir'] . '/' . $meta['file'];
	if( file_exists( $originalfile ) ) {
		$originalurl = $upload_dir['baseurl'] . '/' . $meta['file'];
		$original_response = wp_remote_get( $originalurl, array( 'timeout' => 30 ) );
		if($backup_url) {
			$originalurl2 = $backup_url . '/' . $upload_path . '/' . $meta['file'];
			$original_response2 = wp_remote_get( $originalurl2, array( 'timeout' => 30 ) );
		}
		if( is_wp_error( $original_response ) || ( $backup_url && is_wp_error( $original_response2 ) ) ) {
			$error = true;
			unlink( $originalfile );
		} elseif( 'yes' == $options['delfile'] ) {
			unlink( $originalfile );
		}
	}

	$sizes = $meta['sizes'];
	if( ! empty( $sizes ) && ! $error ) {
		foreach( $sizes as $size ) {
			if( empty( $size['file'] ) ) continue;

			$sizefile = $upload_dir['path'] . '/' . $size['file'];

			if( ! file_exists( $sizefile ) ) continue;

			$sizeurl = $upload_dir['url'] . '/' . $size['file'];
			$sizeurl_response = wp_remote_get( $sizeurl, array( 'timeout' => 30 ) );
			if($backup_url) {
				$sizeurl2 = $backup_url . '/' . $upload_path . $upload_dir['subdir'] . '/' . $size['file'];
				$sizeurl_response2 = wp_remote_get( $sizeurl2, array( 'timeout' => 30 ) );
			}
			if( is_wp_error( $sizeurl_response ) || ( $backup_url && is_wp_error( $sizeurl_response2 ) ) ) {
				$error = true;
				unlink( $sizefile );
			} elseif( 'yes' == $options['delfile'] ) {
				unlink( $sizefile );
			}
		}
	}
	return $error ? '' : $data;
}
add_filter( 'wp_update_attachment_metadata', 'bzg_attachment_cdn_update_attachment_metadata', 10, 2 );

//编辑文章时使用镜像URL
add_filter( 'content_edit_pre', 'bzg_attachment_cdn_the_content', 10, 1 );

//保存文章时把镜像URL替换为本地URL
function bzg_attachment_cdn_content_save( $content ) {
	$content = bzg_attachment_cdn_replace_url( $content, 'DESC' );
	return $content;
}
add_filter( 'content_save_pre', 'bzg_attachment_cdn_content_save', 10, 1 );


//要阻止的代理
function bzg_attachment_cdn_agent( $str ) {
	//代理列表
	$agents = array( 'tencent-httputils', 'qiniu-imgstg-spider' );
	$res = false;
	foreach( $agents as $agent ) {
		if( stripos( $str, $agent ) !== false ) {
			$res = true;
			break;
		}
	}
	return $res;
}
function bzg_attachment_cdn_send_headers() {
	$agent = $_SERVER['HTTP_USER_AGENT'];
	if( bzg_attachment_cdn_agent( $agent ) ) {
		header( 'HTTP/1.1 503 Service Temporarily Unavailable' );
		exit;
	}
}
add_action( 'send_headers', 'bzg_attachment_cdn_send_headers' );
?>
